//
//  JAFCalender.m
//  JAFDemo
//
//  Created by 阿飞 on 2018/1/24.
//  Copyright © 2018年 阿飞. All rights reserved.
//

#import "JAFCalender.h"
#import "JAFCalenderHeader.h"
#import "LXCalendarDayModel.h"
#import "LXCalendarMonthModel.h"
#import "NSDate+GFCalendar.h"
#import "JAFCalenderDayCollectionViewCell.h"
#import "JAFCalenderYearCollectionViewCell.h"
@interface JAFCalender ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property(nonatomic,strong)UICollectionView *collectionViewMonthAndDay;//日历或者月份
@property(nonatomic,strong)UICollectionView *collectionViewYearAndMonth;//月份或者年份
@property(nonatomic,strong)JAFCalenderHeader *calendarHeader; //头部
@property(nonatomic,strong)NSDate *currentMonthDate;//当月的日期
@property(nonatomic,strong)NSMutableArray *monthdataDay;//
@property(nonatomic,strong)NSMutableArray *yearDataMonth;//


@end
//获取屏幕 宽度、高度
#define SCREEN_WIDTH ([[UIScreen mainScreen] bounds].size.width)
#define SCREEN_HEIGHT ([[UIScreen mainScreen] bounds].size.height)
@implementation JAFCalender
-(instancetype)initWithFrame:(CGRect)frame withSearch:(SearchType)type withLeftTitle:(NSString *)leftTitle withRightTitle:(NSString *)rightTitle{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.currentMonthDate = [NSDate date];
        self.searchType = type;
        [self setupWithLeftTitle:leftTitle withRightTitle:rightTitle];
        
        
    }
    return self;
}
#pragma mark---懒加载
//-(JAFCalenderHeader *)calendarHeader{
//    if (!_calendarHeader) {
//        _calendarHeader =[[JAFCalenderHeader alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT*44/667)];
//    }
//
//    return _calendarHeader;
//
//}
-(void)dealData{
    
    [self responDataDay];
    

}
-(void)setupWithLeftTitle:(NSString *)leftTitle withRightTitle:(NSString *)rightTitle{
     self.calendarHeader =[[JAFCalenderHeader alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT*44/667) withLeftTitle:leftTitle withRightTitle:rightTitle];
    [self addSubview:self.calendarHeader];
    __weak typeof(self) weakSelf = self;
    self.calendarHeader.titleClickBlock = ^{
        
        if (weakSelf.isButtonClick) {

            [weakSelf.collectionViewYearAndMonth removeFromSuperview];
            [weakSelf.collectionViewMonthAndDay removeFromSuperview];
            [weakSelf responDataDay];
            weakSelf.isButtonClick = NO;

        }else{
           weakSelf.collectionViewMonthAndDay.hidden = NO;
           weakSelf.collectionViewYearAndMonth.hidden = NO;
            [weakSelf addSubview:weakSelf.collectionViewYearAndMonth];
            [weakSelf addSubview:weakSelf.collectionViewMonthAndDay];
            [weakSelf responDataDay];
            [weakSelf responDataMonth];

            weakSelf.isButtonClick = YES;
        }
        
        
    };
    
    self.calendarHeader.rightClickBlock = ^{
       
        [weakSelf rightSlide];
        
    };
    
    self.calendarHeader.leftClickBlock = ^{
        [weakSelf leftSlide];
    };
    
}
-(NSMutableArray *)monthdataDay{
    if (!_monthdataDay) {
        _monthdataDay =[NSMutableArray array];
    }
    return _monthdataDay;
}

-(NSMutableArray *)yearDataMonth{
    if (!_yearDataMonth) {
        _yearDataMonth =[NSMutableArray array];
    }
    return _yearDataMonth;
}
#pragma mark --左滑处理--
-(void)leftSlide{

     if (self.searchType==SearchTypeDate) {
         
         self.currentMonthDate = [self.currentMonthDate previousMonthDay];
         
     }else{
         
          self.currentMonthDate = [self.currentMonthDate previousMonthDate];
     }
    // [self performAnimations:kCATransitionFromRight];
    [self responDataDay];
    
}
#pragma mark --右滑处理--
-(void)rightSlide{

    if (self.searchType==SearchTypeDate) {
        
       self.currentMonthDate = [self.currentMonthDate nextMonthDay];
        
    }else{
        
        self.currentMonthDate = [self.currentMonthDate nextMonthDate];
        
    }
    //[self performAnimations:kCATransitionFromLeft];
    
    [self responDataDay];
    
}
#pragma mark--数据以及更新处理--
-(void)responDataDay{
    
     [self.monthdataDay removeAllObjects];
//月份
//    NSDate *previousMonthDate = [self.currentMonthDate previousMonthDate];

//    NSDate *nextMonthDate = [self.currentMonthDate  nextMonthDate];
    
 //   NSDate *previousMonthDate = [self.currentMonthDate previousMonthDay];
    
  //  NSDate *nextMonthDate = [self.currentMonthDate  nextMonthDay];
    
    LXCalendarMonthModel *monthModel = [[LXCalendarMonthModel alloc]initWithDate:self.currentMonthDate];
    
//    LXCalendarMonthModel *lastMonthModel = [[LXCalendarMonthModel alloc]initWithDate:previousMonthDate];

//    LXCalendarMonthModel *nextMonthModel = [[LXCalendarMonthModel alloc]initWithDate:nextMonthDate];
    if (self.searchType==SearchTypeDate) {
        self.calendarHeader.dateStr = [NSString stringWithFormat:@"%ld月%ld日",monthModel.month,monthModel.day];
        
        
        if (self.selectBlock) {
            
            self.selectBlock(monthModel.year, monthModel.month, monthModel.day);
            
        }
        
    }else{
         self.calendarHeader.dateStr = [NSString stringWithFormat:@"%ld年%ld月",monthModel. year,monthModel.month];
        
        if (self.selectBlock) {
            
            self.selectBlock(monthModel.year, monthModel.month, monthModel.day);
            
        }
        
    }
if (self.searchType==SearchTypeDate) {
        
    NSInteger totalDays = monthModel.totalDays;
    NSInteger totalMonth = monthModel.totalMonth;
    NSInteger firstWeekday = monthModel.firstWeekday;
    for (int i=0; i<42; i++) {

        LXCalendarDayModel *model =[[LXCalendarDayModel alloc]init];

        //配置外面属性
        [self configDayModel:model];

        //model.firstWeekday = firstWeekday;
        model.totalDays = totalDays;
        model.totalMonth = totalMonth;
        model.month = monthModel.month;
        model.year = monthModel.year;


        //上个月的日期
//        if (i < firstWeekday) {

//            model.day = lastMonthModel.totalDays - (firstWeekday - i) + 1;
//            model.isLastMonth = YES;

//        }

        //当月的日期
        if (i >= firstWeekday && i < (firstWeekday + totalDays)) {

            model.day = i -firstWeekday +1;
            model.isCurrentMonth = YES;

            //标识是今天
            if ((monthModel.month == [[NSDate date] dateMonth]) && (monthModel.year == [[NSDate date] dateYear])) {
                if (i == [[NSDate date] dateDay] + firstWeekday - 1) {

                    model.isToday = YES;

                }
            }

        }
        //下月的日期
//        if (i >= (firstWeekday + monthModel.totalDays)) {
//
//            model.day = i -firstWeekday - nextMonthModel.totalDays +1;
//            model.isNextMonth = YES;
//
//        }

        [self.monthdataDay addObject:model];

     }
    }else{
     
        for (int i = 0; i<13; i++) {
            
            LXCalendarDayModel *model =[[LXCalendarDayModel alloc]init];
            //配置外面属性
            [self configDayModel:model];
            
            model.month = monthModel.month;
            
            NSInteger months = i;
            model.totalMonth = months;
            
            [self.monthdataDay addObject:model];
            
        }
        
    }
     [self.collectionViewMonthAndDay reloadData];
}
-(void)responDataMonth{
    
     [self.yearDataMonth removeAllObjects];
    //月份
    //    NSDate *previousMonthDate = [self.currentMonthDate previousMonthDate];
    //
    //    NSDate *nextMonthDate = [self.currentMonthDate  nextMonthDate];
    
   // NSDate *previousMonthDate = [self.currentMonthDate previousMonthDay];
    
   // NSDate *nextMonthDate = [self.currentMonthDate  nextMonthDay];
    
    LXCalendarMonthModel *monthModel = [[LXCalendarMonthModel alloc]initWithDate:self.currentMonthDate];
    
    //    LXCalendarMonthModel *lastMonthModel = [[LXCalendarMonthModel alloc]initWithDate:previousMonthDate];
    
    //    LXCalendarMonthModel *nextMonthModel = [[LXCalendarMonthModel alloc]initWithDate:nextMonthDate];
//    if (self.searchType==SearchTypeDate)
//    {
//        self.calendarHeader.dateStr = [NSString stringWithFormat:@"%ld月%ld日",monthModel.month,monthModel.day];
//
//
//    }else{
//
//
//
//
//    }
    //self.calendarHeader.dateStr = [NSString stringWithFormat:@"%ld月%ld日",monthModel.month,monthModel.day];
    
    //self.calendarHeader.dateStr = [NSString stringWithFormat:@"%ld年%ld月",monthModel. year,monthModel.month];
    NSLog(@"%ld%ld",(long)monthModel.month,(long)monthModel.day);
   
//    NSInteger totalDays = monthModel.totalDays;
//    NSInteger totalMonth = monthModel.totalMonth;
//    NSInteger firstWeekday = monthModel.firstWeekday;
    
        if (self.searchType==SearchTypeDate)
        {
            for (int i = 0; i<12; i++) {
                
                LXCalendarDayModel *model =[[LXCalendarDayModel alloc]init];
                //配置外面属性
                [self configDayModel:model];
                
                model.month = monthModel.month;
                
                NSInteger months = i+1;
                model.totalMonth = months;
                
            [self.yearDataMonth addObject:model];
            
          }
        }else{
            NSInteger count = -5;
            for (int i = 0; i<13; i++) {
                
                LXCalendarDayModel *model =[[LXCalendarDayModel alloc]init];
                //配置外面属性
                [self configDayModel:model];
                NSInteger years;
                model.year = monthModel.year;
                years = monthModel.year+count;
                count += 1;
                model.totalMonth = years;
                [self.yearDataMonth addObject:model];
                
            }
    
        }
    
    [self.collectionViewYearAndMonth reloadData];
    
}

-(void)configDayModel:(LXCalendarDayModel *)model{
    
    //配置外面属性
    model.isHaveAnimation = self.isHaveAnimation;
    
    model.currentMonthTitleColor = self.currentMonthTitleColor;
    
    model.lastMonthTitleColor = self.lastMonthTitleColor;
    
    model.nextMonthTitleColor = self.nextMonthTitleColor;
    
    model.selectBackColor = self.selectBackColor;
    
    model.isHaveAnimation = self.isHaveAnimation;
    
    model.todayTitleColor = self.todayTitleColor;
    
    model.isShowLastAndNextDate = self.isShowLastAndNextDate;
    
    
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (collectionView==self.collectionViewMonthAndDay) {
        
        return self.monthdataDay.count;
        
    }else{
        
        return  self.yearDataMonth.count;
        
    }
    
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (collectionView == self.collectionViewMonthAndDay) {
        NSString *cellIndentifier = @"cell";
        JAFCalenderDayCollectionViewCell *cell = (JAFCalenderDayCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIndentifier forIndexPath:indexPath];
        if (self.searchType==SearchTypeDate) {
            cell.type = 0;
            cell.model = self.monthdataDay[indexPath.row];
            
        }else{
            cell.type = 1;
            cell.model = self.monthdataDay[indexPath.row];
        }
        
        return cell;
        
    }else{
        
        NSString *cellIndentifier = @"cellMonth";
        JAFCalenderYearCollectionViewCell *cell = (JAFCalenderYearCollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:cellIndentifier forIndexPath:indexPath];
        cell.model = self.yearDataMonth[indexPath.row];
        
        return cell;
    }
    
}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if (collectionView == self.collectionViewYearAndMonth) {
      
        
        LXCalendarDayModel *model = self.yearDataMonth[indexPath.row];
        NSString *yearString = [NSString stringWithFormat:@"%ld",(long)model.totalMonth];
        model.isSelected = YES;
        [self.yearDataMonth enumerateObjectsUsingBlock:^(LXCalendarDayModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {

            if (obj != model) {

                obj.isSelected = NO;
                
            }

        }];
    
        [collectionView reloadData];
        
        //获取系统当前时间
        NSDate *currentDate = [NSDate date];
        //用于格式化NSDate对象
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //设置格式：zzz表示时区
        [dateFormatter setDateFormat:@"yyyy"];
        //NSDate转NSString
        NSString *currentYearString = [dateFormatter stringFromDate:currentDate];
        NSString *currentMonthString = [NSString stringWithFormat:@"%ld",indexPath.row+1];
        
        if (self.searchType==SearchTypeDate) {
            
             [self getSumOfDaysInMonth:currentYearString month:currentMonthString];
            
        }else{
            NSString *currentYearString = [NSString stringWithFormat:@"%@",@"1"];
             [self getSumOfDaysInMonth:yearString month:currentYearString];
        }
        
    }else{
        
        if (self.searchType==SearchTypeDate) {
            LXCalendarDayModel *model = self.monthdataDay[indexPath.row];
            model.isSelected = YES;
            [self.monthdataDay enumerateObjectsUsingBlock:^(LXCalendarDayModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                
                if (obj != model) {
                    obj.isSelected = NO;
                }
            }];
            self.calendarHeader.dateStr = [NSString stringWithFormat:@"%ld月%ld日",model.month,model.day];

            if (self.selectBlock) {
                
                self.selectBlock(model.year, model.month, model.day);
                
            }
             [collectionView reloadData];
            self.collectionViewMonthAndDay.hidden = YES;
            self.collectionViewYearAndMonth.hidden = YES;
            self.isButtonClick = NO;
        }else{
            LXCalendarDayModel *model = self.monthdataDay[indexPath.row];
            
            NSString *indexPathRow = [NSString stringWithFormat:@"%ld",indexPath.row];
            [[NSUserDefaults standardUserDefaults]setObject:indexPathRow forKey:@"indexPathRow"];
            [[NSUserDefaults standardUserDefaults]synchronize];
            //[[NSNotificationCenter defaultCenter]postNotificationName:@"indexPathRow" object:nil];
            model.isSelected = YES;
            [self.monthdataDay enumerateObjectsUsingBlock:^(LXCalendarDayModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {

                if (obj != model) {
                    obj.isSelected = NO;
                }
                
            }];
            
             [collectionView reloadData];
            
            NSString *currentMonthString = [NSString stringWithFormat:@"%ld",indexPath.row];
            NSString *currentYearString = [NSString stringWithFormat:@"%ld",model.year];
            
            if ([currentYearString isEqualToString:@"0"]) {
                
                UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择某年！" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:nil];
                [alertController addAction:okAction];
                
                [self.viewController presentViewController:alertController animated:YES completion:nil];

                
            }else{
                
                [self getSumOfDaysInMonth:currentYearString month:currentMonthString];
                
                self.calendarHeader.dateStr = [NSString stringWithFormat:@"%ld年%ld月",model.year, (long)model.totalMonth];
                if (self.selectBlock) {
                    
                    self.selectBlock(model.year, model.totalMonth, model.day);
                    
                }
                
                self.collectionViewMonthAndDay.hidden = YES;
                self.collectionViewYearAndMonth.hidden = YES;
                self.isButtonClick = NO;
            }
           
        }
    }
    
}
/*
 
 *点击选中月份和日期
 *
 
 */
- (void)getSumOfDaysInMonth:(NSString*)year month:(NSString *)month{
    
    [self.monthdataDay removeAllObjects];
    NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
    
    [formatter setDateFormat:@"yyyy-MM"]; // 年-月
    
    NSString * dateStr = [NSString stringWithFormat:@"%@-%@",year,month];
    
    NSDate * date = [formatter dateFromString:dateStr];
    LXCalendarMonthModel *monthModel = [[LXCalendarMonthModel alloc]initWithDate:date];
//    if (self.searchType == SearchTypeDate) {
//
//      self.calendarHeader.dateStr = [NSString stringWithFormat:@"%ld月%ld日",monthModel.month,monthModel.day];
//
//    }else{
//
//       self.calendarHeader.dateStr = [NSString stringWithFormat:@"%ld年%ld月",monthModel.year,monthModel.month];
//    }
    if (self.searchType==SearchTypeDate) {
        
        NSInteger totalDays = monthModel.totalDays;
        NSInteger totalMonth = monthModel.totalMonth;
        NSInteger firstWeekday = monthModel.firstWeekday;
        for (int i=0; i<42; i++) {
            
            LXCalendarDayModel *model =[[LXCalendarDayModel alloc]init];
            
            //配置外面属性
            [self configDayModel:model];
            
            //model.firstWeekday = firstWeekday;
            model.totalDays = totalDays;
            model.totalMonth = totalMonth;
            model.month = monthModel.month;
            model.year = monthModel.year;
            
            
            //上个月的日期
            //        if (i < firstWeekday) {
            
            //            model.day = lastMonthModel.totalDays - (firstWeekday - i) + 1;
            //            model.isLastMonth = YES;
            
            //        }
            
            //当月的日期
            if (i >= firstWeekday && i < (firstWeekday + totalDays)) {
                
                model.day = i -firstWeekday +1;
                model.isCurrentMonth = YES;
                
                //标识是今天
                if ((monthModel.month == [[NSDate date] dateMonth]) && (monthModel.year == [[NSDate date] dateYear])) {
                    if (i == [[NSDate date] dateDay] + firstWeekday - 1) {
                        
                        model.isToday = YES;
                        
                    }
                }
                
            }
            //下月的日期
            //        if (i >= (firstWeekday + monthModel.totalDays)) {
            //
            //            model.day = i -firstWeekday - nextMonthModel.totalDays +1;
            //            model.isNextMonth = YES;
            //
            //        }
            
            [self.monthdataDay addObject:model];
            
        }
    }else{
        
        for (int i = 0; i<13; i++) {
            
            LXCalendarDayModel *model =[[LXCalendarDayModel alloc]init];
            //配置外面属性
            [self configDayModel:model];
            
            model.month = monthModel.month;
            model.year = monthModel.year;
            NSInteger months = i;
            model.totalMonth = months;
            
            [self.monthdataDay addObject:model];
            
        }
        
    }
    
    [self.collectionViewMonthAndDay reloadData];
    
}
-(UICollectionView *)collectionViewYearAndMonth{
    
    if (!_collectionViewYearAndMonth) {
        UICollectionViewFlowLayout *flow =[[UICollectionViewFlowLayout alloc]init];
        flow.minimumInteritemSpacing = 0;
        flow.minimumLineSpacing = 0;
        flow.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        flow.sectionInset =UIEdgeInsetsMake(0, 0, 0, 0);
        flow.itemSize = CGSizeMake(SCREEN_WIDTH/7, 50);
        _collectionViewYearAndMonth =[[UICollectionView alloc]initWithFrame:CGRectMake(0, 55,SCREEN_WIDTH, 50) collectionViewLayout:flow];
        _collectionViewYearAndMonth.delegate = self;
        _collectionViewYearAndMonth.dataSource = self;
        _collectionViewYearAndMonth.showsVerticalScrollIndicator = NO;
        _collectionViewYearAndMonth.showsHorizontalScrollIndicator = NO;
        _collectionViewYearAndMonth.scrollsToTop = NO;
        _collectionViewYearAndMonth.backgroundColor = [UIColor whiteColor];
        [_collectionViewYearAndMonth registerClass:[JAFCalenderYearCollectionViewCell class] forCellWithReuseIdentifier:@"cellMonth"];
        
        
    }
    return _collectionViewYearAndMonth;
}
-(UICollectionView *)collectionViewMonthAndDay{
    if (!_collectionViewMonthAndDay) {
        
        UICollectionViewFlowLayout *flow =[[UICollectionViewFlowLayout alloc]init];
        flow.minimumInteritemSpacing = 0;
        flow.minimumLineSpacing = 0;
        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        flow.sectionInset =UIEdgeInsetsMake(0, 0, 0, 0);
        flow.itemSize = CGSizeMake(SCREEN_WIDTH/7, 50);
        _collectionViewMonthAndDay =[[UICollectionView alloc]initWithFrame:CGRectMake(20, 110,SCREEN_WIDTH-40, 300) collectionViewLayout:flow];
        _collectionViewMonthAndDay.delegate = self;
        _collectionViewMonthAndDay.dataSource = self;
        _collectionViewMonthAndDay.showsVerticalScrollIndicator = NO;
        _collectionViewMonthAndDay.showsHorizontalScrollIndicator = NO;
        _collectionViewMonthAndDay.scrollsToTop = YES;
        _collectionViewMonthAndDay.backgroundColor = [UIColor whiteColor];
        [_collectionViewMonthAndDay registerClass:[JAFCalenderDayCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
       // _collectionViewMonthAndDay.backgroundColor = [UIColor yellowColor];
    }
    return _collectionViewMonthAndDay;
}

/*
 * 当前月的title颜色
 */
-(void)setCurrentMonthTitleColor:(UIColor *)currentMonthTitleColor{
    _currentMonthTitleColor = currentMonthTitleColor;
}
/*
 * 上月的title颜色
 */
-(void)setLastMonthTitleColor:(UIColor *)lastMonthTitleColor{
    _lastMonthTitleColor = lastMonthTitleColor;
}
/*
 * 下月的title颜色
 */
-(void)setNextMonthTitleColor:(UIColor *)nextMonthTitleColor{
    _nextMonthTitleColor = nextMonthTitleColor;
}

/*
 * 选中的背景颜色
 */
-(void)setSelectBackColor:(UIColor *)selectBackColor{
    _selectBackColor = selectBackColor;
}

/*
 * 选中的是否动画效果
 */

-(void)setIsHaveAnimation:(BOOL)isHaveAnimation{
    
    _isHaveAnimation  = isHaveAnimation;
}

/*
 * 是否禁止手势滚动
 */
-(void)setIsCanScroll:(BOOL)isCanScroll{
    _isCanScroll = isCanScroll;
    
    //self.leftSwipe.enabled = self.rightSwipe.enabled = isCanScroll;
}

/*
 * 是否显示上月，下月的按钮
 */

-(void)setIsShowLastAndNextBtn:(BOOL)isShowLastAndNextBtn{
    _isShowLastAndNextBtn  = isShowLastAndNextBtn;
   // self.calendarHeader.isShowLeftAndRightBtn = isShowLastAndNextBtn;
}

/*
 * 是否显示上月，下月的的数据
 */
-(void)setIsShowLastAndNextDate:(BOOL)isShowLastAndNextDate{
    _isShowLastAndNextDate =  isShowLastAndNextDate;
}
/*
 * 今日的title颜色
 */

-(void)setTodayTitleColor:(UIColor *)todayTitleColor{
    _todayTitleColor = todayTitleColor;
}

@end
